import json
import logging
from datetime import datetime

from airflow.patsnap.util.page_util import Pagination
from airflow.models.idata_auth_resource import AuthResource
from airflow.models.idata_auth_role import AuthRole
from airflow.models.idata_auth_role_resource import AuthRoleResource
from airflow.utils.session import create_session, provide_session

log = logging.getLogger(__name__)


@provide_session
def get_role(rid, session: None):
    role = AuthRole.get_role(rid, None, session)
    resources = AuthResource.get_resource(None, rid, session)
    role.resources = resources
    return role


@provide_session
def get_roles(page, session: None):
    if page == 0:
        roles = AuthRole.get_roles(session)
        for role in roles:
            rid = role.id
            resources = AuthResource.get_resource(None, rid, session)
            role.resources = resources
        map_roles = map(AuthRole.to_json, roles)
        return list(map_roles)
    else:
        role_result = AuthRole.get_roles_page(page, session)
        for role in role_result.items:
            rid = role.id
            resources = AuthResource.get_resource(None, rid, session)
            role.resources = resources
        role_result.items = list(map(AuthRole.to_json, role_result.items))
        result = role_result.to_json()
        return result


def delete_role(role_id):
    with create_session() as session:
        AuthRole.delete_role(role_id, session)
        AuthRoleResource.delete_role_resource_by_roleid(role_id, session)


def add_role(role_name, weight, resource_ids):
    role = AuthRole(role_name, weight, datetime.now())
    AuthRole.add_roles(role)
    for resource_id in resource_ids:
        role_resource = AuthRoleResource(resource_id, role.id, datetime.now())
        AuthRoleResource.add_roles_resources(role_resource)


@provide_session
def update_role(role_id, role_name, weight, resource_ids, session=None):
    role = AuthRole(role_name, weight, datetime.now())
    role.id = role_id
    AuthRole.update_role(role, session)
    AuthRoleResource.delete_role_resource_by_roleid(role_id, session)
    for resource_id in resource_ids:
        role_resource = AuthRoleResource(resource_id, role_id, datetime.now())
        AuthRoleResource.add_roles_resources(role_resource, session)
